﻿using System;
using System.Windows.Input;

namespace OmniKits.Windows
{
  public class StacklessCommand<T> : ICommand
  {
    public event EventHandler CanExecuteChanged;
    public event StacklessEventHandler<T> ExecuteInvoked;
    public event StacklessEventHandler<T, bool> CanExecuteInvoked;

    public bool CanExecute(object parameter)
    {
      var value = (T)parameter;

      var handler = CanExecuteInvoked;
      if (handler == null)
        return true;

      return new StacklessEventArgs<T, bool>(value).InvokeEventHandler(this, handler);
    }

    public void FireCanExecuteChanged()
      => CanExecuteChanged?.Invoke(this, EventArgs.Empty);

    public void Execute(object parameter)
      => new StacklessEventArgs<T>((T)parameter).InvokeEventHandler(this, ExecuteInvoked);
  }
}
